<template>
  <AppModal ref="modalRef" width="500px">
    <el-form ref="formRef" :model="formModel" label-width="auto">
      <el-form-item
        :label="type + '名称'"
        name="name"
        :rules="[{ required: true, message: '此为必填项' }]"
      >
        <el-input
          :placeholder="`请输入${type}名称`"
          v-model="formModel.name"
        ></el-input>
      </el-form-item>
      <el-form-item
        :label="type + '编码'"
        name="code"
        :rules="[{ required: true, message: '此为必填项' }]"
      >
        <el-input
          :disabled="modalAction != 'add'"
          :placeholder="`请输入${type}编码`"
          v-model="formModel.code"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注" name="remark">
        <el-input
          type="textarea"
          placeholder="请输入备注"
          v-model="formModel.remark"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序">
        <el-input type="number" v-model="formModel.weight"></el-input>
      </el-form-item>
    </el-form>
  </AppModal>
</template>

<script setup lang="ts">
import { AppModal } from "@/components/common";
import { useForm } from "@/hooks/useForm.ts";
import { DictDto } from "@/api/dict.ts";
import { useModal } from "@/hooks/useModal.ts";
import { ElMessage } from "element-plus";

const props = defineProps<{
  type: string;
}>();
const emits = defineEmits(["add", "update"]);
const { formRef, formModel, validation, restFields, initForm } =
  useForm<DictDto>({
    name: null,
    code: null,
    remark: "",
    weight: 0,
  });
const { modalRef, okLoading } = useModal();
const modalAction = ref("");

function onOpen(action: string, row?: DictDto) {
  modalAction.value = action;
  initForm();
  if (row) {
    formModel.value = { ...row };
  }

  restFields();
  modalRef.value.open({
    title: action == "add" ? "新增" + props.type : "编辑" + props.type,
    onOk: onSubmit,
  });
}

function onSubmit() {
  validation().then(() => {
    okLoading.value = true;
    if (modalAction.value == "add") {
      emits("add", unref(formModel), (success: boolean) => {
        okLoading.value = false;
        if (success) {
          modalRef.value.close();
          ElMessage.success("添加成功");
        }
      });
    } else {
      emits("update", unref(formModel), () => {
        okLoading.value = false;
        modalRef.value.close();
        ElMessage.success("更新成功");
      });
    }
  });

  return false;
}

defineExpose({ onOpen });
</script>

<style scoped></style>
